<?php
/*
 * Created on Feb 12, 2010
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */

include('../includes/session.php');
include('../models/userinfo_model.php');

class UserInfoController{
	
	function UserInfoController(){
		global $session;
		if(isset($_POST['useredit'])){
        	$this->userEdit();
     	}else if(isset($_POST['userlogin'])){
     		$this->userLogin();
     	}
		/* User submitted registration form */
      	else if(isset($_POST['userregister'])){
        	$this->userRegister();
     	} else if(isset($_POST['register'])){
        	$this->register();
     	} else if($session->logged_in){
        	$this->userLogout();
     	}
		else{       		
        	header("Location: ".$session->referrer);
       	}
	}
	
	function userLogout(){
		global $session;  //The database connection
      
      	if(isset($_COOKIE['cookname']) && isset($_COOKIE['cookid'])){
         	setcookie("cookname", "", time()-COOKIE_EXPIRE, COOKIE_PATH);
         	setcookie("cookid",   "", time()-COOKIE_EXPIRE, COOKIE_PATH);
      	}

      	/* Unset PHP session variables */
      	unset($_SESSION['username']);
      	unset($_SESSION['userid']);

      	/* Reflect fact that user has logged out */
      	$session->logged_in = false;      
      	$session->removeActiveUser($session->username);
      	$session->addActiveGuest($_SERVER['REMOTE_ADDR'], $this->time);
      
      	/* Set user level to guest */
      	$session->username  = GUEST_NAME;
      	$session->userlevel = GUEST_LEVEL;
		
		header("Location: ".$session->referrer);
   	}
	
	function userLogin(){
		global $session, $form, $userModel;
	  	$retval = 0;
		$username = $_POST['username'];
		$password = $_POST['password'];
		$level = $_POST['userlevel'];
		$isremember = $_POST['remember'];
		
		if(isset($_POST['captchafield']) && !empty($_POST['captchafield']) && 
			!empty($_SESSION['captcharees']) && trim(strtolower($_POST['captchafield'])) == $_SESSION['captcharees']){
			/* Username error checking */
			$field = "user";  //Use field name for username
		    if(!$username || strlen($username = trim($username)) == 0){
		    	$form->setError($field, prnMsg(_('Nhập tài khoản'),'error'));
		    }
		    else{
			    /* Check if username is not alphanumeric */
			    if(!eregi("^([0-9a-z])*$", $username)){
			        $form->setError($field, prnMsg(_('Tài khoản không thuộc alphanumeric'),'error'));
			    }
	      	}
	
	      	/* Password error checking */
	      	$field = "pass";  //Use field name for password
	      	if(!$password){
	         	$form->setError($field, prnMsg(_('Nhập mật khẩu'),'error'));
	      	}
	      
	      	/* Return if form errors exist */
	      	if($form->num_errors > 0){
	        	$retval = 1;
	      	}else{
	      		/* Login attempt */
				$username = stripslashes($_POST['username']);
				$password = md5($_POST['password']);
	      		$retval = $userModel->login($username, $password, $level);
				/* Check error codes */
		      	if($retval == 1){
		         	$field = "user";
		        	$form->setError($field, prnMsg(_('Tài khoản không tìm thấy'),'error'));
		      	}
		      	else if($retval == 2){
		         	$field = "pass";
		         	$form->setError($field, prnMsg(_('Mật khẩu không chính xác'),'error'));
		      	}
		      
		      	/* Return if form errors exist */
		      	if($form->num_errors > 0){
		         	$retval = 1;
		      	}			
	      	}      		
		}else{
			$field = "captcha";
		    $form->setError($field, prnMsg(_('Nhập mã an ninh không đúng.'),'error'));
			$retval = 1;
		}
		
	    /* Login successful */
	    if($retval == 0){
	    	
	    	/* Username and password correct, register session variables */
			$userModel->updateUserField($username, 'lastLoginDate', date('Y-m-d h:i:s'));
			$user  = $userModel->getUserByUsername($username);
		    $username  = $_SESSION['username'] = $user['userName'];
		    $userid    = $_SESSION['userid']   = $user['id'];
		   
		    /* Insert userid into database and update active users table */
		    $session->addActiveUser($username, time());
		    $session->removeActiveGuest($_SERVER['REMOTE_ADDR']);
						
			if($isremember){
		    	setcookie("cookname", $username, time()+COOKIE_EXPIRE, COOKIE_PATH);
		        setcookie("cookid",   $userid,   time()+COOKIE_EXPIRE, COOKIE_PATH);
		    }
	  		
	    	header("Location: ".$session->referrer);
	    }
	    /* Login failed */
	    else{
	    	$_SESSION['value_array'] = $_POST;
	        $_SESSION['error_array'] = $form->getErrorArray();
	        header("Location: ".$session->referrer);
	    }
   }
   
	function userEdit(){
		global $session, $form;
		$resultValidation = 0;
		$checkPassword = 0;
		/* password error checking */
		$password = null;
	    $field = "password";
		if(isset($_POST['password']) && !empty($_POST['password'])){
			if($_POST['password'] != $_POST['password2']){
				$checkPassword = 1;
				$resultValidation = 1;
	    		$form->setError($field, prnMsg(_('Nhập lại mật khẩu'),'error'));
			}else{
				$password = $_POST['password'];
			}
		}
			
		if($checkPassword == 0){
			$resultValidation = $this->checkValidation(
										$_POST['SelectedUser'],
										$_POST['userName'], 
										$password,
										$_POST['email'], 
										$_POST['fullName'],
										$_POST['place'],
										$_POST['phone'],
										$_POST['statusFlag'],
										null);
		}
		/* Account edit successful */
	    if($resultValidation == 0){
	    	$_SESSION['edit'] = true;
			$_SESSION['editname'] = $_POST['fullName'];
	        header("Location: ".$session->referrer);
	    }
	    /* Error found with form */
	    else{
			$_SESSION['edit'] = false;
	        $_SESSION['value_array'] = $_POST;
	        $_SESSION['error_array'] = $form->getErrorArray();
	        header("Location: ".$session->referrer);
		}
	}
	
	function register(){
		global $session, $form;
		if(ALL_LOWERCASE){
        	$_POST['userName'] = strtolower($_POST['userName']);
     	}
		$resultValidation = 0;
		if(isset($_POST['captchafield']) && !empty($_POST['captchafield']) && 
			!empty($_SESSION['captcharees']) && trim(strtolower($_POST['captchafield'])) == $_SESSION['captcharees']){			
			/* password error checking */
			$field = "password";  //Use field name for email
			if(!$_POST['password'] || strlen($_POST['password'] = trim($_POST['password'])) == 0){
				$resultValidation = 1;
				$form->setError($field, prnMsg(_('Nhập mật khẩu'),'error'));
			}
			else{
				if($_POST['password'] == $_POST['password2']){
					$resultValidation = $this->checkValidation(
												null,
												$_POST['userName'], 
												$_POST['password'],
												$_POST['email'], 
												$_POST['fullName'],
												$_POST['place'],
												$_POST['phone'],
												1,
												$_POST['createDate']);
				}else{
					$resultValidation = 1;
					$form->setError($field, prnMsg(_('Nhập lại mật khẩu'),'error'));
				}
			}
		}else{
			$field = "captcha";
		    $form->setError($field, prnMsg(_('Nhập mã an ninh không đúng.'),'error'));
			$resultValidation = 1;
		}
		/* Registration Successful */
		if($resultValidation == 0){
	    	$_SESSION['successname'] = $_POST['fullName'];
	        $_SESSION['success'] = true;
	        header("Location: ".$session->referrer);
	    }
	    /* Error found with form */
	    else if($resultValidation == 1){
	        $_SESSION['value_array'] = $_POST;
	        $_SESSION['error_array'] = $form->getErrorArray();
	        header("Location: ".$session->referrer);
	    }
	    /* Registration attempt failed */
	    else if($resultValidation == 2){
	        $_SESSION['successname'] = $_POST['userName'];
	        $_SESSION['success'] = false;
	        header("Location: ".$session->referrer);
	    }
	}
	
	function userRegister(){
		global $session, $form;
		if(ALL_LOWERCASE){
        	$_POST['userName'] = strtolower($_POST['userName']);
     	}
		$resultValidation = 0;
		/* password error checking */
	    $field = "password";
	    if(!$_POST['password'] || strlen($_POST['password'] = trim($_POST['password'])) == 0){
	    	$resultValidation = 1;
	    	$form->setError($field, prnMsg(_('Nhập mật khẩu'),'error'));
	    }
	    else{
	    	if($_POST['password'] == $_POST['password2']){
	    		$resultValidation = $this->checkValidation(
											null,
											$_POST['userName'], 
											$_POST['password'],
											$_POST['email'], 
											$_POST['fullName'],
											$_POST['place'],
											$_POST['phone'],
											$_POST['statusFlag'],
											$_POST['createDate']);
	    	}else{
	    		$resultValidation = 1;
	    		$form->setError($field, prnMsg(_('Nhập lại mật khẩu'),'error'));
	    	}
	   	}
		/* Registration Successful */
		if($resultValidation == 0){
	    	$_SESSION['successname'] = $_POST['fullName'];
	        $_SESSION['success'] = true;
	        header("Location: ".$session->referrer);
	    }
	    /* Error found with form */
	    else if($resultValidation == 1){
	        $_SESSION['value_array'] = $_POST;
	        $_SESSION['error_array'] = $form->getErrorArray();
	        header("Location: ".$session->referrer);
	    }
	    /* Registration attempt failed */
	    else if($resultValidation == 2){
	        $_SESSION['successname'] = $_POST['user'];
	        $_SESSION['success'] = false;
	        header("Location: ".$session->referrer);
	    }
	}
	
	function checkValidation($userID = null, $subuser, $subpass, $subemail, $subFullName, $subPlace, $subPhone, $status, $createDate){
		global $form, $userModel;
		/* Username error checking */
      	$field = "userName";  //Use field name for username
	    if(!$subuser || strlen($subuser = trim($subuser)) == 0){
	    	$form->setError($field, prnMsg(_('Nhập tài khoản đăng nhập'),'error'));
	    }
	    else{
	    	/* Spruce up username, check length */
	        $subuser = stripslashes($subuser);
	        if(strlen($subuser) < 5){	        	
	        	$form->setError($field, prnMsg(_('Tài khoản lớn hơn 5 ký tự'),'error'));
	        }
	        else if(strlen($subuser) > 30){
	        	$form->setError($field, prnMsg(_('Tài khoản nhỏ hơn 30 ký tự'),'error'));
	        }
	        /* Check if username is not alphanumeric */
	        else if(!eregi("^([0-9a-z])+$", $subuser)){
	        	$form->setError($field, prnMsg(_('Tài khoản không thuộc alphanumeric'),'error'));
	        }
	        /* Check if username is reserved */
	        else if(strcasecmp($subuser, GUEST_NAME) == 0){
	        	$form->setError($field, prnMsg(_('Tài khoản bị đảo ngược'),'error'));
	        }
	        /* Check if username is already in use */
	      /*  else if($database->usernameTaken($subuser)){
	        	$form->setError($field, "* Username already in use");
	        }*/
		}
		
		if($subpass != null) {		
			$field = "password";  //Use field name for username
			if(strlen($subpass) < 6){	        	
				$form->setError($field, prnMsg(_('Mật khẩu lớn hơn 6 ký tự'),'error'));
			}else if(strlen($subpass) > 30){
				$form->setError($field, prnMsg(_('Mật khẩu nhỏ hơn 30 ký tự'),'error'));
			}
			/* Check if username is not alphanumeric */
			else if(!eregi("^([0-9a-z])+$", $subpass)){
				$form->setError($field, prnMsg(_('Mật khẩu không thuộc alphanumeric'),'error'));
			}else{
				$subpass = md5($subpass);
			}
		}
		
		/* Email error checking */
	    $field = "email";  //Use field name for email
	    if(!$subemail || strlen($subemail = trim($subemail)) == 0){
	    	$form->setError($field, prnMsg(_('Nhập Email'),'error'));
	    }
	    else{
	    	/* Check if valid email address */
	        $regex = "^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*"
	                 ."@[a-z0-9-]+(\.[a-z0-9-]{1,})*"
	                 ."\.([a-z]{2,}){1}$";
	        if(!eregi($regex,$subemail)){
	        	$form->setError($field, prnMsg(_('Email không đúng'),'error'));
	        }
	        $subemail = stripslashes($subemail);
	   	}
		  
		/* FullName error checking */
	    $field = "fullName";  //Use field name for email
	    if(!$subFullName || strlen($subFullName = trim($subFullName)) == 0){
	    	$form->setError($field, prnMsg(_('Nhập họ tên'),'error'));
	      }
		  
		/* FullName error checking */
	    $field = "place";  //Use field name for email
	    if(!$subPlace || strlen($subPlace = trim($subPlace)) == 0){
	    	$form->setError($field, prnMsg(_('Nhập địa chỉ'),'error'));
	    }
		  
		/* FullName error checking */
	    $field = "phone";  //Use field name for email
	    if(!$subPhone || strlen($subPhone = trim($subPhone)) == 0){
	        $form->setError($field, prnMsg(_('Nhập số điện thoại'),'error'));
	    }	
		
		/* Errors exist, have user correct them */
	    if($form->num_errors > 0){
	    	return 1;  //Errors with form
	    }/* No errors, add the new account to the */		
	    else{			
	    	if(!isset($userID)){
				if($userModel->userNameTaken($subuser) == false){
					return $userModel->addNewUser($subuser, $subpass, $subemail, $subFullName, $subPlace, $subPhone, $status, $createDate);
				}else{
					$field = "userName";
					$form->setError($field, prnMsg(_('Tài khoản đăng nhập đã tồn tại. Vui lòng tạo tài khoản khác.'),'error'));
					return 1;
				}
			}else{
				return $userModel->editUser($userID, $subpass, $subemail, $subFullName, $subPlace, $subPhone, $status);
			}
	   	}
	}
};

/* Create userinfo controller object */
$userController = new UserInfoController;
?>